<template>
  <div class="reply-box">
    <div class="article-comment">
      <div class="user-head">
        <img v-if="level===0"
             class="wh48 circle-h pointer ld ld-by-hover ld-shiver"
             :src="getGravatar(sender.head)"
             alt=""
             title="用户配置"
             @click="openDialog('userDialog')"
        >
      </div>
      <div class="comment-editor"
           ref="msg"
           :class="{small:level>0}"
           contenteditable="true"
           placeholder="留个评论撒"
           @click="changeSelection"
           @keyup.stop="changeSelection"
      >
      </div>
    </div>

    <div class="comment-action">
      <div class="comment-action-icon wh42">
        <i ref='emojiBtn' class="far fa-smile wh42 circle-h" @click.stop="openDialog('showEmoji',$event)"></i>
        <div v-if="showEmoji"
             class="emoji-container"
             :class="{'up':showEmojiTop,'down':!showEmojiTop}"
             @click.stop
        >
          <div class="emoji-container-head">
            <div class="tab-head">
                  <span class="tab-item"
                        :class="{active:emojiTab.id===v.id}"
                        v-for="(v,i) in emoji"
                        :key="i"
                        @click.stop="emojiTab=v">
                    <img class="icon-emoji" :src="v.baseUrl+v.icon" alt="">
                  </span>
            </div>
            <div class="emoji-desc">
              {{ emojiTab.name }}
            </div>
          </div>

          <vue-scroll>
            <div class="relative-full">
              <div class="emoji-list">
                    <span class="icon-emoji-container fl"
                          v-for="(v,i) in emojiTab.items"
                          :key="i"
                          @click.stop="insertEmoji(emojiTab.baseUrl+v)"
                    >
                      <img class="icon-emoji" :src="emojiTab.baseUrl+v" alt="">
                    </span>
              </div>

              <div v-if="emojiTab.id===1" style="font-size: 12px;font-weight: 300;color:#ccc;padding: 2px 6px">
                Icons made by
                <a href="https://www.flaticon.local/authors/freepik" title="Freepik">Freepik</a>
                from
                <a href="https://www.flaticon.local/" title="Flaticon">www.flaticon.local</a>
              </div>

              <div v-if="emojiTab.id===2" style="font-size: 12px;font-weight: 300;color:#ccc;padding: 2px 6px">
                Icons made by
                <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a>
                from
                <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>
              </div>
            </div>
          </vue-scroll>
        </div>
      </div>
      <button class="daisy-btn primary-btn round"
              :class="{large:level===0}"
              @click="sendComment"
      >发送 <i class="ml-5 far fa-paper-plane"></i></button>

      <milk-dialog v-if="userDialog"
                   title="修改你的信息"
                   :light="true"
                   @close="userDialog=false">
        <div>
          <milk-input v-model="userInfoTemp.name"
                      :show-button="false"
                      label="昵称"
                      label-color="#a175ed"
          ></milk-input>
        </div>
        <div class="mt-10">
          <milk-input v-model="userInfoTemp.head"
                      :show-button="false"
                      label="头像"
                      label-color="#a175ed"
                      aria-placeholder="输入你的邮箱(gravatar)"
          ></milk-input>
        </div>
        <div slot="foot" class="f-y-center pt-5">
          <button class="daisy-btn warn-btn ml-auto" @click="userDialog=false">取 消</button>
          <button class="daisy-btn primary-btn ml-10" @click="saveUserInfo">保 存</button>
        </div>
      </milk-dialog>
    </div>
  </div>
</template>

<script>
import userMixin from '@/views/mixins/userMixin'
import emoji from '@/libs/emoji'
import util from '@/libs/util'
import { UpdateArticleComment } from '@/api/blog-api'

export default {
  name: 'ReplyBox',
  mixins: [userMixin],
  props: {
    level: {
      type: Number,
      default: 0
    },
    articleId: String,
    parent: {
      type: Object,
      default: function () {
        return null
      }
    }
  },
  data () {
    return {
      emoji,
      emojiTab: '',
      lastSelection: null,
      showEmoji: false,
      showEmojiTop: true,
    }
  },
  created () {
    this.emojiTab = emoji[0]
  },
  mounted () {
    this.$refs.msg.focus()
    this.changeSelection()
    this.$refs.msg.blur()
    window.addEventListener('click', this.closeEmoji)
  },
  beforeDestroy () {
    window.removeEventListener('click', this.closeEmoji)
  },
  methods: {
    changeSelection () {
      this.lastSelection = window.getSelection().getRangeAt(0)
      // console.log(this.lastSelection)
    },

    insertEmoji (src) {
      let newNode = document.createElement('img')
      newNode.setAttribute('src', src)
      newNode.setAttribute('class', 'icon-emoji')
      newNode.setAttribute('style', 'padding:0 4px')
      this.lastSelection.insertNode(newNode)
      this.lastSelection.setEndAfter(newNode)
      this.lastSelection.setStartAfter(newNode)
      var j = window.getSelection()
      j.removeAllRanges()
      j.addRange(this.lastSelection)
      this.$refs.msg.focus()
    },

    openDialog (dialog, e) {
      if (dialog === 'userDialog') {
        this.openUserInfoDialog()
        this[dialog] = true
      }
      if (dialog === 'showEmoji') {
        if (this[dialog] === false) {
          // console.log(e)
          if (document.body.clientHeight - this.$refs.emojiBtn.getBoundingClientRect().bottom > 350) {
            this.showEmojiTop = false
          } else {
            this.showEmojiTop = true
          }
        }
        this[dialog] = !this[dialog]
      }
    },

    // keepalive 所以这个事件一直都在
    closeEmoji () {
      this.showEmoji = false
    },

    validateMessage (msg) {
      let reg = /^\s*$/g
      if (reg.test(msg)) {
        alert('信息不能为空')
        this.$refs.msg.innerHTML = ''
        return false
      }
      return true
    },

    sendComment () {
      if (this.sender.head === '') {
        alert('请点击评论框的头像添加你的邮箱！')
        return
      }
      if (!this.validateMessage(this.$refs.msg.innerHTML)) {
        return
      }
      let msg = this.$refs.msg.innerHTML

      let postMsg =
          {
            id: util.guid(),
            content: msg,
            sendTime: util.time.localTime(),
            user: this.convertUserHead(),
            level: this.level,
            parent: this.parent.id ? this.parent.parent.concat(this.parent.id) : [],
            comments: []
          }
      // console.log(postMsg)
      this.$emit('afterComment', postMsg)
      this.$refs.msg.innerHTML = ''
      UpdateArticleComment({ articleId: this.articleId, comment: postMsg }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },

    saveUserInfo () {
      this.updateUserInfo()
    },
  },
}
</script>

<style>

.reply-box {
  width: 100%;
}

.article-comment {
  width: 100%;
  padding: 14px 0;
  display: flex;
}

.user-head {
  flex: 0 0 60px;
  padding-top: 10px;
  padding-right: 10px;
}

.comment-editor {
  outline: none;
  font-size: 15px;
  flex: 1;
  padding: 26px 14px 34px 0;
  margin-left: 4px;
  border-bottom: 1px solid #ccc;
  overflow-x: hidden;
}

.comment-editor.small {
  padding-top: 10px;
  padding-bottom: 20px;
}

.comment-editor:empty:before {
  cursor: text;
  content: attr(placeholder);
  color: #bbb;
}

.comment-editor:focus {
  content: none;
}

.comment-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 54px;
}

.comment-action-icon {
  position: relative;
  cursor: pointer;
  color: #6c6ce5;
  font-size: 24px;
  text-align: center;
  transition: .35s;
}

.comment-action-icon > i {
  line-height: 42px;
}

.comment-action-icon > i:hover {
  background-color: #e6e6fd;
}

.emoji-container {
  position: absolute;
  width: 260px;
  height: 320px;
  padding-top: 84px;
  border-radius: 8px;
  background-color: #FFFFFF;
  left: -80px;
  box-shadow: rgba(101, 119, 134, 0.2) 0px 0px 15px,
  rgba(101, 119, 134, 0.15) 0px 0px 3px 1px;
  z-index: 1;
}

.emoji-container.up {
  bottom: 52px;
}

.emoji-container.down {
  top: 52px;
}

.emoji-container::before {
  content: "";
  display: block;
  position: absolute;
  left: 94px;
  height: 16px;
  width: 16px;
  background-color: #FFFFFF;
  box-shadow: -2px 2px 3px 0 rgba(101, 119, 134, 0.2);
}

.emoji-container.up::before {
  bottom: -8px;
  transform: rotate(-45deg);
}

.emoji-container.down::before {
  top: -8px;
  transform: rotate(135deg);
}

.emoji-container-head {
  position: absolute;
  top: 0;
  width: 100%;
  height: 84px;
}

.tab-head {
  position: relative;
  padding: 0 4px 1px;
  border-bottom: 1px solid #eee;
  height: 45px;
}

.tab-item {
  cursor: pointer;
  position: relative;
  float: left;
  bottom: -2px;
  width: 42px;
  height: 43px;
  padding: 5px;
  border-bottom: 2px solid transparent;
  z-index: 1;
}

.tab-item:hover {
  background-color: #e6e6ff;
  border-bottom: 2px solid #e6e6ff;
}

.tab-item.active {
  border-bottom: 2px solid #9292ff;
}

.emoji-desc {
  padding: 10px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #2e333a;
  border-bottom: 1px solid #eee;
}

.emoji-list {
  padding: 10px;
  overflow: hidden;
}

</style>
